/*
 * Created on Apr 4, 2004
 *
 */
package littlecyberwar.control.net;

import java.lang.Thread;
import littlecyberwar.util.*;
import littlecyberwar.ui.*;
import littlecyberwar.model.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

/**
 * @author Milton  Soong
 *
 * This task will take as the input the InputStream, create a task that listens on the 
 * steam, and then put the change into the model
 * 
 * Incoming Task is a "pseudo" thread, no new thread is created. Instead it is running 
 * on the server or client thread that was spawn off
 * 
 */
public class IncomingTask {
	ModelChangeFacade mod;
	ObjectInputStream oi;
	Players thisPlayer;
	
	public IncomingTask( InputStream is ){
		mod = ModelChangeFacade.getInstance();
		try {
			oi = new ObjectInputStream( is );
		} catch ( IOException ex ){
			// !!! eventually put up a user dialog
			ex.printStackTrace();
		}
		return;
	}
	
	public void start() {
		String playerName=null;
		try {
			playerName = (String)oi.readObject();
		} catch ( SocketException ex ){
			MainFrame mf = MainFrame.getInstance();
			JOptionPane.showMessageDialog(mf,
				"Your opponent has disconnected the game",
				"Opponent Disconnected",
				JOptionPane.ERROR_MESSAGE);							
	 
		} catch ( Exception ex ){
			ex.printStackTrace();
		}
		thisPlayer = new Players(playerName, false);

		while( true ){
			Command cmd=null;
			try {
				cmd = (Command)oi.readObject();
			} catch ( SocketException ex ){
				MainFrame mf = MainFrame.getInstance();
				JOptionPane.showMessageDialog(mf,
					"Your opponent has disconnected the game",
					"Opponent Disconnected",
					JOptionPane.ERROR_MESSAGE);							
	 			break;
	 			
		   	} catch ( Exception ex ){
				ex.printStackTrace();
			}
			mod.addCmd(cmd);
		}
	}

}
